package ncme.auto.framework.core.interceptor;

import com.auth0.jwt.exceptions.AlgorithmMismatchException;
import com.auth0.jwt.exceptions.SignatureVerificationException;
import com.auth0.jwt.exceptions.TokenExpiredException;
import com.fasterxml.jackson.databind.ObjectMapper;
import ncme.auto.framework.core.exceptions.AutoException;
import ncme.auto.framework.core.exceptions.ExceptionEnum;
import ncme.auto.framework.core.utils.JwtUtil;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

@Configuration
public class JwtInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        Map<String, Object> map = new HashMap<>();
        //token放在请求头里，不要放在请求体中
        String token = request.getHeader("token");
        try {
            if (request.getMethod().equals("OPTIONS")) {
                response.setStatus(HttpServletResponse.SC_OK);
                return true;
            }
            JwtUtil.verify(token);
            return true;    //放行
        } catch (SignatureVerificationException e) {
            map.put("state", false);
            map.put("code", ExceptionEnum.TOKEN_ERROR.getCode());
            map.put("msg", "无效签名");
        } catch (TokenExpiredException e) {
            map.put("state", false);
            map.put("code", ExceptionEnum.TOKEN_ERROR.getCode());
            map.put("msg", "token过期");
        } catch (AlgorithmMismatchException e) {
            map.put("state", false);
            map.put("code", ExceptionEnum.TOKEN_ERROR.getCode());
            map.put("msg", "token算法不一致");
        } catch (AutoException e) {
            if (ExceptionEnum.getExceptionEnum(e.getCode()) == ExceptionEnum.LOGIN_OUT) {
                map.put("state", false);
                map.put("code", ExceptionEnum.LOGIN_OUT.getCode());
                map.put("msg", e.getMessage());
            } else {
                map.put("state", false);
                map.put("code", ExceptionEnum.TOKEN_ERROR.getCode());
                map.put("msg", "token无效");
            }
        } catch (Exception e) {
            map.put("state", false);
            map.put("code", ExceptionEnum.TOKEN_ERROR.getCode());
            map.put("msg", "token无效");
        }

        String responseJson = new ObjectMapper().writeValueAsString(map);  //map转为json
        response.setContentType("application/json;charset=UTF-8");
        response.getWriter().println(responseJson);

        return false;
    }
}
